//
//  FCForgetPasswordVC.m
//  FundChain
//
//  Created by 肖浩然的mac on 2018/2/7.
//  Copyright © 2018年 RUIXIN. All rights reserved.
//

#import "FCForgetPasswordVC.h"
#import "FCResetPasswordVC.h"
@interface FCForgetPasswordVC ()<UITextFieldDelegate>

/* 邮箱 */
@property (strong, nonatomic) UITextField *emailField;

/* 提交 */
@property (strong, nonatomic) UIButton *submitBtn;

/* 忘记密码 */
@property (strong, nonatomic) UITextField *passwordField;
@end

@implementation FCForgetPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showBackItem = YES;
    [FCLocalUserHelper saveIsMainVC:@"0"];
    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [self setupUI];
}

#pragma mark-设置UI
-(void)setupUI{
    //背景图片
    UIImageView *bgImageView = [UIImageView new];
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    bgImageView.image = [UIImage imageNamed:@"bg_login"];
    //忘记密码label
    UILabel *forgetPasswordLabel = [UILabel new];
    [self.view addSubview:forgetPasswordLabel];
    [forgetPasswordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                make.left.mas_equalTo(32*KScreenWidthScale750);
                make.top.mas_equalTo((100)*KScreenHeightScale1334);
                
            }else{
                make.left.mas_equalTo(32*KScreenWidthScale750);
                make.top.mas_equalTo(100*KScreenHeightScale1334);
                
            }
        }else{
            make.left.mas_equalTo(32*KScreenWidthScale750);
            make.top.mas_equalTo(100*KScreenHeightScale1334);
            
        }
    }];
    forgetPasswordLabel.text = Localized(@"忘记密码");
    forgetPasswordLabel.font = KOverstrikingfont(52);
    //提示语
    UILabel *hintLabel = [UILabel new];
    [self.view addSubview:hintLabel];
    [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(forgetPasswordLabel);
        make.top.mas_equalTo(forgetPasswordLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.right.mas_equalTo(-55*KScreenWidthScale750);
    }];
    hintLabel.font = Kfont(28);
    hintLabel.textColor = kGrayColor;
    hintLabel.text = Localized(@"请输入您的电子邮件地址。验证码将被发送到邮箱。");
    hintLabel.numberOfLines = 2;
    //邮箱标题
    UILabel *emailLabel = [UILabel new];
    [self.view addSubview:emailLabel];
    [emailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(forgetPasswordLabel);
        make.top.mas_equalTo(hintLabel.mas_bottom).offset(120*KScreenHeightScale1334);
        
    }];
    emailLabel.font = Kfont(32);
    emailLabel.textColor = kGrayColor;
    emailLabel.text = Localized(@"邮箱");
    //输入邮箱
    UITextField *emailField = [UITextField new];
    self.emailField = emailField;
    [self.view addSubview:emailField];
    [emailField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(emailLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(forgetPasswordLabel);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
    emailField.keyboardType = UIKeyboardTypeURL;
    NSString *emailStr = [FCLocalUserHelper getUserEmailStr];
    emailField.text = emailStr;
    //分割线
    UIView *viewLine1 =[UIView new];
    [self.view addSubview:viewLine1];
    [viewLine1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(emailField);
        make.top.mas_equalTo(emailField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine1.backgroundColor =kLineColor;
    //密码标题
    UILabel *passwordLabel = [UILabel new];
    [self.view addSubview:passwordLabel];
    [passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(forgetPasswordLabel);
        make.top.mas_equalTo(viewLine1.mas_bottom).offset(80*KScreenHeightScale1334);
        
    }];
    passwordLabel.font = Kfont(32);
    passwordLabel.textColor = kGrayColor;
    passwordLabel.text = Localized(@"验证码");
    //输入密码
    UITextField *passwordField = [UITextField new];
    self.passwordField = passwordField;
    [self.view addSubview:passwordField];
    [passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(passwordLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(forgetPasswordLabel);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
    passwordField.delegate = self;
    passwordField.keyboardType = UIKeyboardTypeNumberPad;
     [passwordField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    //分割线
    UIView *viewLine2 =[UIView new];
    [self.view addSubview:viewLine2];
    [viewLine2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(passwordField);
        make.top.mas_equalTo(passwordField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine2.backgroundColor =kLineColor;
    
    //发送验证码
    UIButton *sendBtn = [UIButton new];
    [self.view addSubview:sendBtn];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(viewLine2.mas_right);
        make.bottom.mas_equalTo(viewLine2.mas_top).offset(5);
    }];
    [sendBtn setTitle:Localized(@"发送验证码") forState:(UIControlStateNormal)];
    [sendBtn setTitleColor:kRedOrangeColor forState:UIControlStateNormal];
    sendBtn.titleLabel.font = Kfont(32);
    //分割线
    UIView *viewLine3 =[UIView new];
    [self.view addSubview:viewLine3];
    [viewLine3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(sendBtn.mas_left).offset(-20*KScreenWidthScale750);
        make.height.mas_equalTo(32*KScreenHeightScale1334);
        make.bottom.mas_equalTo(sendBtn).offset(-8);
        make.width.mas_equalTo(1);
    }];
    viewLine3.backgroundColor =kLineColor;
    
    
    //提交按钮
    UIButton *submitBtn = [UIButton new];
    self.submitBtn = submitBtn;
    [self.view addSubview:submitBtn];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30*KScreenWidthScale750);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
        make.bottom.mas_equalTo(-100*KScreenHeightScale1334);
        make.height.mas_equalTo(112*KScreenHeightScale1334);
    }];
    submitBtn.layer.cornerRadius = 5.0;
    submitBtn.layer.masksToBounds = YES;
    submitBtn.titleLabel.font = KOverstrikingfont(36);
    [submitBtn setTitle:Localized(@"提交") forState:(UIControlStateNormal)];
    [submitBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [submitBtn setBackgroundColor:kLightblueColor];
    
    //事件
    [passwordField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingDidEnd];
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [sendBtn addTarget:self action:@selector(sendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark-textfieldDelegate
-(void)textFieldDidChange:(UITextField *)textField{
    
    
    if(self.passwordField == textField ){
        if (self.emailField.text.trimWhitespace.length > 0 && self.passwordField.text.trimWhitespace.length > 0) {
            
            [self.submitBtn setBackgroundColor:kRedOrangeColor];
        }else{
            [self.submitBtn setBackgroundColor:kLightblueColor];
        }
    }
}
-(void)textFieldChange:(UITextField*)textField{
    if (textField.text.trimWhitespace.length > 6) {
        textField.text = [textField.text substringToIndex:6];
        
    }
    
}
#pragma mark-提交
-(void)submitBtnClick:(UIButton*)sender{
    
    if (self.emailField.text.trimWhitespace.length <= 0 || self.passwordField.text.trimWhitespace.length <= 0 ) {
        return;
        
    }
    if ([FCLocalUserHelper isValidateEmail:self.emailField.text.trimWhitespace]) {
        
    }else{
        [self showAlert:Localized(@"请输入正确的邮箱")];
        return;
    }
    if (self.passwordField.text.trimWhitespace <0) {
        [self showAlert:Localized(@"请输入验证码")];
        return;
    }
    
    [self showChrysanthemumAlert:nil];
    NSString *url = Email_verification_URL;
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:1];
    [dict setObject:self.emailField.text.trimWhitespace forKey:@"email"];
    [dict setObject:self.passwordField.text.trimWhitespace forKey:@"ems"];
    [FCSharedNetworkTool POSTWithURLString:url parameters:dict success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        NSNumber *two = [NSNumber numberWithInteger:200];
        NSNumber *four = [NSNumber numberWithInteger:400];
        NSNumber *four1 = [NSNumber numberWithInteger:404];
        if (dic[@"code"] == two) {
            //获取emailTken,保存
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self hideProgress];
                FCResetPasswordVC *vc = [FCResetPasswordVC new];
                vc.emailToken = dic[@"result"][@"emailToken"];
                vc.emailStr = self.emailField.text.trimWhitespace;
                [self.navigationController pushViewController:vc animated:NO];
                
            });
            
        }else if (dic[@"code"] == four){
            [self hideProgress];
            [self showAlert:Localized(@"验证码不正确或已过期。")];
        }else if (dic[@"code"] == four1){
            [self hideProgress];
            [self showAlert:Localized(@"验证码不正确或已过期。")];
        }
    } faile:^(NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }
        
    }];
    
    
    
    
 
}

#pragma mark-发送验证码
-(void)sendBtnClick:(UIButton*)sender{
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
    if (self.emailField.text.length <= 0) {
        return;
    }
    
    [self showChrysanthemumAlert:nil];
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置 特别注明：UI的改变一定要在主线程中进行
                [sender setTitle:Localized(@"发送验证码") forState:UIControlStateNormal];
                [sender setTitleColor:kRedOrangeColor forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
        }else{
            
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.submitBtn setBackgroundColor:kRedOrangeColor];
                [sender setTitleColor:kLightblueColor forState:UIControlStateNormal];
                [sender setTitle:[NSString stringWithFormat:@"%@(%@s)",Localized(@"重发"),strTime] forState:UIControlStateNormal];
                
                sender.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
   //发送验证码
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setObject:self.emailField.text.trimWhitespace forKey:@"email"];
    NSString *languageStr;
    Language language = [CLanguageUtil getCurrentLanguage];
    switch (language) {
        case Language_Hans:
        {
            languageStr = @"cn";
        }
            break;
        case Language_Hant:
        {
            languageStr = @"hk";
        }
            break;
        case Language_EN:
        {
             languageStr = @"en";
        }
            break;
        default:
            break;
    }
     [dic setObject:languageStr forKey:@"language"];
      [dic setObject:@"verify" forKey:@"action"];
    NSString *url = [NSString stringWithFormat:@"%@",Send_emile_ems_URL];
    [FCSharedNetworkTool POSTWithURLString:url parameters:dic success:^(id responseObject) {
        if (responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary *dict = responseObject;
            NSNumber *two = [NSNumber numberWithInteger:200];
            if (dict[@"code"] == two) {
                NSLog(@"发送成功");
                [self hideProgress];
                [self showAlert:Localized(@"验证码发送成功")];
            }else if ([dict[@"code"] integerValue] == 404){
                [self hideProgress];
                [self showAlert:Localized(@"验证码发送失败")];
            }
        }
        
    } faile:^(NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }
        
    }];
    
    
}
#pragma mark - 键盘弹出时界面上移及还原
-(void)keyBoardWillShow:(NSNotification *) notification{
    
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int keyBoardHeight = keyboardRect.size.height;
    
    //使视图上移
    CGRect viewFrame = self.view.frame;
    
    viewFrame.origin.y = -keyBoardHeight/2;//上移1/2的键盘高度
    self.view.frame = viewFrame;
    
}

- (void)keyBoardWillHide:(NSNotification *) notification {
    //当键盘消失时执行方法使视图下滑回原位
    NSTimeInterval time = [[notification.userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    [UIView animateWithDuration:time animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = 64;
        self.view.frame = frame;
        [self.view layoutIfNeeded];
    }];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //移除第一响应
    [self.emailField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    
}
@end
